package game;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VideoControl;
import javax.microedition.midlet.MIDlet;
import javax.microedition.m2g.ExternalResourceHandler;
import javax.microedition.m2g.SVGAnimator;
import javax.microedition.m2g.SVGEventListener;
import javax.microedition.m2g.SVGImage;
import javax.microedition.m2g.ScalableImage;

import org.w3c.dom.Document;
import org.w3c.dom.svg.SVGElement;

/**
 * Midlet Class
 * 
 * @author Group C03
 * @author Mona Khlousy
 * @author Heba El-Samahi 
 * @author Daniel Schobert
 * 
 * @since 18.02.2009
 */

public class LUMM2_Midlet extends MIDlet implements CommandListener, PlayerListener {

        /** application state */
        private LUMM2_Canvas pc;
        private GameCanvas gc;
        
        private static SVGAnimator svgAnimator;
        
        /** Displays*/  
        private static Display display;
        public GameCanvas currentDisplay;
        
        public GameCanvas lastDisplay;
        
        private Form mMainScreen;
        private Item mVideoItem;

        private VideoControl mVidc;
        private Player mPlayer = null;
        private boolean menu;
        
        /**
         * LUMM2_Midlet constructor
         */

        public LUMM2_Midlet() {
                System.gc();
                display = Display.getDisplay(this);
                menu = false;
                if (mMainScreen == null) {
                    mMainScreen = new Form("                   D I G   D U G");
                    String tmp = "\n\n\n\n";
                    mMainScreen.append(tmp);
                    mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
                    mMainScreen.addCommand(new Command("Skip Intro", Command.SCREEN, 0));
                    mMainScreen.setCommandListener(this);
                  }
                playFromResource();
        }
        
        /**
         * plays the intro video
         */
        private void playFromResource() {
            try {
              InputStream in = getClass().getResourceAsStream("/intro_mini.mp4");
              mPlayer = Manager.createPlayer(in, "video/mpeg");
              mPlayer.realize();
              if ((mVidc = (VideoControl) mPlayer.getControl("VideoControl")) != null) {
                mVideoItem = (Item) mVidc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
                mVideoItem.setLayout(Item.LAYOUT_CENTER);
                mMainScreen.append(mVideoItem);
              }
              mPlayer.start();
              display.setCurrent(mMainScreen);
              mPlayer.addPlayerListener(this);
            } catch (Exception e) {
              System.out.print("exception caught while trying to create player for intro vid");
            }
          }
        
        /**
         * method inherited from CommandListener interface
         * handles exit and skip-intro command
         * @param c : command which has to be handled
         * @param d : 
         */
        public void commandAction(Command c, Displayable d) {
			if (c.getCommandType() == Command.EXIT) {
			      destroyApp(true);
			      notifyDestroyed();
			    } else if (c.getLabel().equals("Skip Intro")){
			    	try {
						mPlayer.stop();
					} catch (MediaException e) {
						System.out.print("could not stop intro vid");
					}
			    	mPlayer = null;
			    	System.gc();
			    	startmenu();
			    }
			
		}
        
        /**
         * starts the SVG menu
         */
        private void startmenu(){
        	pc = new LUMM2_Canvas(this);
        	menu = true;
            InputStream is = getClass().getResourceAsStream("/menue.svg");
        	try{
                SVGImage svgMenue = (SVGImage)SVGImage.createImage(is, new ImageHandler());
                svgAnimator = SVGAnimator.createAnimator(svgMenue);
                gc = (GameCanvas)svgAnimator.getTargetComponent();
                svgAnimator.setSVGEventListener(new MIDPSVGEventListener(svgAnimator, svgMenue));       
            } catch (IOException e) {       
        		e.printStackTrace();
        		System.out.println("Could not load image!");
        		gc = pc;
        	}
            startApp();
        }
        
        /**
         * method inherited from interface PlayerLister, called if player 
         * changes his state
         * 
         * needed for end of media event --> menu
         */
        public void playerUpdate(Player player, String event, Object eventData) {
			if (event.equals(END_OF_MEDIA)) {
				player.close();
				player = null;
				mPlayer = null;
		    	System.gc();
		    	startmenu();
			} 
		}

        /**
         * start midlet
         */

        public void startApp() {
        	if (menu){
        		if (LUMM2_Game.currentGameState == LUMM2_Game.MENU) {
                        LUMM2_Midlet.svgAnimator.play();
                        display.setCurrent(gc);
                }else {
                        pc.addCommand(LUMM2_Canvas.CMD_BACK);
                        pc.addCommand(LUMM2_Canvas.CMD_EXIT);
                        pc.setCommandListener(pc);
                        display.setCurrent(pc);
                }
        	}
        }

        /**
         * pause midlet
         */

        public void pauseApp() {
                // TODO
        }

        /**
         * destroy midlet
         * 
         * @param unconditional
         */

        public void destroyApp(boolean unconditional) {
                // TODO
                
        }
        
        public static void flashBacklight(int dur){

                display.flashBacklight(dur);
        }

        
        class MIDPSVGEventListener implements SVGEventListener {
                
            private byte PLAY = 0;
            private byte HIGHSCORE = 1;
            private byte SETTINGS = 2;
            int currentMenuElement = PLAY;
            private SVGAnimator svgAnimator;
            private SVGElement selected;
            private SVGElement dugselected;
            private Document doc;
            
                
                public MIDPSVGEventListener(SVGAnimator svgAnimator, SVGImage svgImage) {
                        this.svgAnimator = svgAnimator;
                        this.doc = svgImage.getDocument();
                        this.selected = (SVGElement)doc.getElementById("select");
                        this.dugselected = (SVGElement)doc.getElementById("dug");
                }

            public void keyPressed(int keystate) {
                //System.out.println(keystate);
                if(keystate == -5) { //enter
                        svgAnimator.stop();
                        if(currentMenuElement == PLAY){
                                LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                                LUMM2_Game.currentGameState = LUMM2_Game.PLAY;
                        }
                        else if(currentMenuElement == HIGHSCORE){
                                LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                                LUMM2_Game.currentGameState = LUMM2_Game.HIGHSCORE;
                        }
                        else if(currentMenuElement == SETTINGS){
                                LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                                LUMM2_Game.currentGameState = LUMM2_Game.SETTINGS;
                        }else{
                                notifyDestroyed();
                                destroyApp(true);
                        }
                        startApp();
                }
                else if(keystate == -1) { //up
                        //Berechnet das aktuelle Menueelement
                        currentMenuElement = ((currentMenuElement-1)+4)%4;
                        selected.setTrait("y", (currentMenuElement*30)+89+"");
                        dugselected.setTrait("y", (currentMenuElement*30)+89+"");       
                }
                else if(keystate == -2) { //down
                        currentMenuElement = ((currentMenuElement+1)+4)%4;
                        selected.setTrait("y", (currentMenuElement*30)+89+"");
                        dugselected.setTrait("y", (currentMenuElement*30)+89+"");
                }
                else if(keystate == 49){
                        svgAnimator.stop();
                        LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                        LUMM2_Game.currentGameState = LUMM2_Game.PLAY;
                        startApp();
                }
                else if(keystate == 50){
                        svgAnimator.stop();
                        LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                        LUMM2_Game.currentGameState = LUMM2_Game.HIGHSCORE;
                        startApp();
                }
                else if(keystate == 51){
                        svgAnimator.stop();
                        LUMM2_Game.lastGameState = LUMM2_Game.currentGameState;
                        LUMM2_Game.currentGameState = LUMM2_Game.SETTINGS;
                        startApp();
                }
                else if(keystate == 52){
                        svgAnimator.stop();
                        notifyDestroyed();
                        destroyApp(true);
                }               
            }
            
            public void keyReleased(int k) { /* ... */ }
            public void hideNotify() { /* ... */ }
            public void pointerPressed(int a, int b) { /* ... */ }
            public void pointerReleased(int a, int b) { /* ... */ }
            public void showNotify() { /* ... */ }
            public void sizeChanged(int a, int b) { /* ... */ }
        }


		

        
}

class ImageHandler implements ExternalResourceHandler {
        public void requestResource(final ScalableImage scalableImage,
        final String URI) {
        final InputStream inputStream = Image.class.getResourceAsStream(URI);

        if (inputStream == null)
        System.out.println("Failed to load " + URI);

        try {
        scalableImage.requestCompleted(URI, inputStream);
        } catch (final IOException e) {
        e.printStackTrace();
        }
        }
        }